import { getStore } from "@/util/store";

export const isUR = (s) => /^http[s]?:\/\/.*/.test(s);

// 对象转换成字符串参数
export const objToform = (obj) => {
  const result = [];
  Object.keys(obj).forEach(ele => {
    result.push(`${ele}=${obj[ele]}`);
  });
  return result.join("&");
};

// 设置标题
export const setTitle = (title) => {
  title = title ? `${title}——${this.$defaultTitle}` : this.$defaultTitle;
  document.title = title;
};

// 关闭标签
export const closeTag = (value) => {
  const tag = value || this.$store.getters.tag;
  this.$store.commit("DEL_TAG", tag);
};

// 处理路由
export const getPath = (params) => {
  let project = getStore({ name: "project" }) || {};
  let token = getStore({ name: "access_token" }) || "";
  const { src } = params;
  let result = src || "/";
  if (src.includes("http") || src.includes("https")) {
    // 组装url上的动态参数并且对url进行escape转码
    params.src = filterUrlEncode(params.src);
    params.menuSrc = params.src;
    params.src = result.replace(/\{projectName\}/g, project.projectName).replace(/\{projectNo\}/g, project.projectNo).replace(/\{token\}/g, token);
    result = `/myiframe/urlPath?${objToform(params)}`;
  }
  return result;
};

// 1. +  URL 中+号表示空格 %2B
// 2. 空格 URL中的空格可以用+号或者编码 %20
// 3. /  分隔目录和子目录 %2F
// 4. ?  分隔实际的 URL 和参数 %3F
// 5. % 指定特殊字符 %25
// 6. # 表示书签 %23
// 7. & URL 中指定的参数间的分隔符 %26
export const filterUrlEncode = (url) => url.replace(/\?/g, "%3F").replace(/\&/g, "%26");

// 正则处理路由
export const vaildPath = (list, path) => {
  let result = false;
  list.forEach(ele => {
    if (new RegExp("^" + ele + ".*", "g").test(path)) {
      result = true;
    }
  });
  return result;
};

// 设置路由值
export const getValue = (route) => {
  let value = "";
  if (route.query.src) {
    value = route.query.src;
  } else {
    value = route.path;
  }
  return value;
};

/**
 * 深拷贝
 */
// eslint-disable-next-line require-jsdoc
export const utils_deepClone = (obj) => {
  if (typeof obj !== "object") {
    return obj;
  }
  var newObj = (Object.prototype.toString.call(obj) === "[object Array]") ? [] : {};
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = (typeof obj[key] !== "object") ? obj[key] : utils_deepClone(obj[key]);
    }
  }
  return newObj;
};
